import Phaser from "phaser";
import { MainScene } from "../scenes";

export class Card extends Phaser.Physics.Arcade.Sprite {

    private cooldownDuration = 3000
    private cooldownTime = 0
    private cooldownMask
    private maskGraphics

    constructor(scene: MainScene, x: number, y: number, texture: string | Phaser.Textures.Texture, frame?: string | number) {
        super(scene, x, y, texture, frame)
        scene.add.existing(this)
        scene.physics.add.existing(this)
        this.setInteractive()
        this.on('pointerdown', () => {
            if (this.cooldownTime <= 0&&scene.diamond>=50) {
                scene.handler.toActive(texture, this)
            }
        })

        this.maskGraphics = this.scene.add.graphics()
        this.maskGraphics.fillStyle(0x1677ff, 0.2)
        this.maskGraphics.moveTo(this.x - this.width / 2, this.y - this.height / 2)
        this.maskGraphics.lineTo(this.x + this.width / 2, this.y - this.height / 2)
        this.maskGraphics.lineTo(this.x + this.width / 2, this.y + this.height / 2)
        this.maskGraphics.lineTo(this.x - this.width / 2, this.y + this.height / 2)
        this.maskGraphics.closePath()
        this.maskGraphics.fill()

        this.cooldownMask = this.maskGraphics.createGeometryMask()
        this.setMask(this.cooldownMask)
        this.startCooldown()
    }

    protected preUpdate(time: number, delta: number): void {
        super.preUpdate(time, delta)

        if (this.cooldownTime > 0) {
            this.cooldownTime -= delta
            const progress = Phaser.Math.Clamp(1 - this.cooldownTime / this.cooldownDuration, 0, 1)

            this.maskGraphics.clear()
            this.maskGraphics.fillStyle(0x1677ff, 0.2)
            this.maskGraphics.moveTo(this.x - this.width / 2, this.y - this.height / 2)
            this.maskGraphics.lineTo(this.x + this.width / 2, this.y - this.height / 2)
            this.maskGraphics.lineTo(this.x + this.width / 2, this.y + this.height / 2 - this.height * progress)
            this.maskGraphics.lineTo(this.x - this.width / 2, this.y + this.height / 2 - this.height * progress)
            this.maskGraphics.closePath()
            this.maskGraphics.fill()

            this.maskGraphics.fillStyle(0x1677ff, 0)
            this.maskGraphics.moveTo(this.x - this.width / 2, this.y + this.height / 2 - this.height * progress)
            this.maskGraphics.lineTo(this.x + this.width / 2, this.y + this.height / 2 - this.height * progress)
            this.maskGraphics.lineTo(this.x + this.width / 2, this.y + this.height / 2)
            this.maskGraphics.lineTo(this.x - this.width / 2, this.y + this.height / 2)
            this.maskGraphics.closePath()
            this.maskGraphics.fill()
        }
    }

    startCooldown() {
        this.cooldownTime = this.cooldownDuration
    }
}